package fr.snac.utils;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Environment;

public class FilesUtil {

	public static String getPostFolderPath(){

		File dlDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
		return dlDirectory.getPath() + "/" + Constants.BM_FOLDER_NAME + "/" + Constants.BM_FOLDER_POSTS;
	}
	
	public static String getImageFolderPath(){

		File dlDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
		return dlDirectory.getPath() + "/" + Constants.BM_FOLDER_NAME + "/" + Constants.BM_FOLDER_IMAGES;
	}	

	public static boolean isInfosFileCreated(){
		
		File postFolder = new File(getPostFolderPath());
		String[] list = postFolder.list();
		
		if (list == null || list.length == 0)
			return false;
		
		for (String s : list){
			if (s.startsWith(Constants.BM_FILENAME_INFOS))
				return true;
		}
		
		return false;
	}
	
	public static boolean imageAlreadyDownloaded(String imageDate){

		File bmFolder = new File(getImageFolderPath());

		String[] list = bmFolder.list();

		if (list == null)
			return false;

		for (String s : bmFolder.list()){
			if (s.startsWith(imageDate))
				return true;
		}

		return false;
	}

	
	public static void createFolders(){

		File dlDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

		FileFilter folderFilter = new FileFilter() {

			@Override
			public boolean accept(File pathname) {

				if (pathname.getName().equals(Constants.BM_FOLDER_NAME))
					return true;
				return false;
			}
		};

		FileFilter imgPostFilter = new FileFilter() {

			@Override
			public boolean accept(File pathname) {
				if (pathname.getName().equals(Constants.BM_FOLDER_IMAGES) || pathname.getName().equals(Constants.BM_FOLDER_POSTS))
					return true;
				return false;
			}
		};

		File[] folder = dlDirectory.listFiles(folderFilter);
		File bmFolder;

		if (folder == null || folder.length == 0){
			bmFolder = new File(dlDirectory.getPath() + "/" + Constants.BM_FOLDER_NAME);
			bmFolder.mkdirs();

			File imagesFolder = new File(bmFolder.getPath() + "/" + Constants.BM_FOLDER_IMAGES);
			File postsFolder = new File(bmFolder.getPath() + "/" + Constants.BM_FOLDER_POSTS);

			imagesFolder.mkdir();
			postsFolder.mkdir();
		}else{
			bmFolder = folder[0];
			File[] dataFolders = bmFolder.listFiles(imgPostFilter);

			if (dataFolders == null || dataFolders.length == 0){
				File imagesFolder = new File(bmFolder.getPath() + "/" + Constants.BM_FOLDER_IMAGES);
				File postsFolder = new File(bmFolder.getPath() + "/" + Constants.BM_FOLDER_POSTS);

				imagesFolder.mkdir();
				postsFolder.mkdir();
			}
		}

	}
	
	public static String getImageType(String imageDate){
		
		File bmFolder = new File(getImageFolderPath());
		String[] list = bmFolder.list();

		if (list == null)
			return null;
		
		String pattern = "(\\w*)(\\.[a-z]{2,4})";
		Pattern p = Pattern.compile(pattern);

		for (String s : bmFolder.list()){
			if (s.startsWith(imageDate)){
				Matcher m = p.matcher(s);
				if (m.find()) return m.group(2); 
			}
		}

		return ".png";
	}
	
	@SuppressLint("UseSparseArrays")
	public static void keepLastMadames(SharedPreferences settings){
		
		int i = 0;
		int photoKept = settings.getInt(Constants.SETTINGS_PHOTO_KEPT, 10);
		
		
		
		File imageFolder = new File(getImageFolderPath());

		String[] files = imageFolder.list();
		ArrayList<Calendar> dates = new ArrayList<Calendar>();
		Map<Integer, File> images = new HashMap<Integer, File>();

		if (files == null || files.length == 0)
			return;

		for (String s : files){
			
			s = s.substring(0, s.length() - 4);
			
			String[] date = s.split("-");

			int year = Integer.parseInt(date[0]);
			int month = Integer.parseInt(date[1]) - 1;
			int day = Integer.parseInt(date[2]);

			Calendar calendar = new GregorianCalendar(year, month, day);
			dates.add(calendar);
		}
		
		files = null;
		Collections.sort(dates);
		
		
		for (Calendar c : dates){
			
			//String fileName = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) + ".png"; 
			String fileName = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH);
			File img = new File(imageFolder.getPath() + "/" + fileName + getImageType(fileName));
			images.put(i, img);
			i++;
		}
		
		if (settings != null)
			photoKept = settings.getInt(Constants.SETTINGS_PHOTO_KEPT, 10);
		
		int len = dates.size();
		int end = len - photoKept;
		
		for (i = 0; i < end; i++)		
			images.get(i).delete();
		
		images.clear();
		dates.clear();
	}
	
	@SuppressLint("UseSparseArrays")
	public static String getLastPicture(){
		File imageFolder = new File(getImageFolderPath());

		String[] files = imageFolder.list();
		ArrayList<Calendar> dates = new ArrayList<Calendar>();


		for (String s : files){
			
			s = s.substring(0, s.length() - 4);
			
			String[] date = s.split("-");

			int year = Integer.parseInt(date[0]);
			int month = Integer.parseInt(date[1]) - 1;
			int day = Integer.parseInt(date[2]);

			Calendar calendar = new GregorianCalendar(year, month, day);
			dates.add(calendar);
		}
		
		files = null;
		Collections.sort(dates);
		
		String lastDate = DateUtil.getUSDate(dates.get(dates.size() - 1)); 
		
		//Log.d("FILESUTIL", lastDate);
		
		return lastDate;
	}
	
	public static String getSourceName(String url){
		
		String[] splits = url.split("/");
		
		return splits[splits.length - 1];
	}
	
	public static void clearImagesFolder(){
		
		File folder = new File(getImageFolderPath());
		
		for (File f : folder.listFiles())
			f.delete();
		
		folder = null;
	}
	
	public static void clearCacheFolder(){
		
		File folder = new File(getPostFolderPath());
		
		for (File f : folder.listFiles())
			f.delete();	
		
		folder = null;
	}
}
